package com.hulk.other.Thread.ConsumerAndProducer;

/**
 * @author CUIJIAJUN
 * @date 2016年10月20日
 * 
 */
public class ConsumerAndProducer {
	public static void main(String[] args) {
//		No enclosing instance of type ConsumerAndProducer is accessible.
		ConsumerAndProducer ca = new ConsumerAndProducer();
		Box box = ca.new Box();
		Producer p = ca.new Producer(box);
		Consumer c = ca.new Consumer(box);
		new Thread(p).start();
		new Thread(c).start();

	}

	class Food {
		int id;

		Food(int id) {
			this.id = id;
		}

		public String toString() {
			return "Food : " + this.id;
		}
	}

	class Box {
		int index = 0;
		Food[] arrFood = new Food[6];

		public synchronized void put(Food food) {
			while (index == arrFood.length) {
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			this.notifyAll();
			arrFood[index++] = food;
		}

		public synchronized Food get() {
			while (index == 0) {
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			this.notifyAll();
			return arrFood[--index];
		}

	}

	class Producer implements Runnable {

		Box box = null;

		Producer(Box box) {
			this.box = box;
		}

		public void run() {
			for (int i = 0; i < 20; i++) {
				Food food = new Food(i);
				System.out.println("Put : " + food);
				box.put(food);
				try {
					Thread.sleep((int) (Math.random() * 100));
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	class Consumer implements Runnable {

		Box box = null;

		Consumer(Box box) {
			this.box = box;
		}

		public void run() {
			for (int i = 0; i < 20; i++) {
				Food food = box.get();
				System.out.println("Get : " + food);
				try {
					Thread.sleep((int) (Math.random() * 200));
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}